<template>
	<view class="content" :style="{ height: windowHeight + 'px' }">
		<view class="view">
			<scroll-view @scrolltolower="lowerBottom" class="box_scroll" scroll-y="true" refresher-enabled="true"
				:refresher-triggered="triggered" :refresher-threshold="50" refresher-background="#f8f8f8"
				@refresherrefresh="onRefresh" @refresherrestore="onRestore">
				<view class="box_list_noData" v-if="productList.length == 0 && !downRefresh">
					<image class="noData_img"
						src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/29/1753765605533_4b17a9fa/icon_zanwushuju.png?x-oss-process=image/resize,w_300"
						mode="" />
					<view class="noData_text">
						暂无数据
					</view>
				</view>
				<view class="items" v-for="(item, index) in productList" :key="index">
					<view class="header">
						<view class="title">{{ item.name }}</view>
						<view class="pre">{{ item.isCorrect ? '正确' : '错误' }}</view>
					</view>
					<view class="bottom">
						<view class="answer">您的答案是：{{ item.type != '多选' ? item.userAnswer : '' }}
							{{ item.userAnswerOption || '' }}
						</view>
						<view class="date">{{ item.createTime }}</view>
					</view>
					<view class="correct_answers">
						<view class="tiltes">{{ item.type != '多选' ? item.answer : '' }} {{ item.answerOption || '' }}
						</view>
						<view>正确答案</view>
					</view>
					<view class="answer_subject">
						<view class="font">
							<view>
								解答
							</view>
							<image class="laba" @click="labaClick(item.answerDesc || '', item)" v-if="!item.isPlay"
								src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/29/1753776125617_e66f11aa/bofang.png?x-oss-process=image/resize,w_300" mode="" />
							<image class="laba" @click="zantingaClick(item)" v-else src="https://dujiaojing.oss-cn-huhehaote.aliyuncs.com/uploads/2025/7/29/1753776196939_06b6089f/zanting.png?x-oss-process=image/resize,w_300"
								mode="" />
						</view>
						<view class="cometmt">{{ item.answerDesc || '' }}</view>
					</view>
				</view>
				<u-loadmore v-if="productList.length != 0" fontSize="25" :status="status" />
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import {
		systemInfo
	} from '../../utils/mixin'
	import {
		getIncorrect,
		getAliTtsSts
	} from '@/api/index.js'
	export default {
		components: {},
		mixins: [systemInfo],
		data() {
			return {
				productList: [],
				queryParams: {
					pageNum: 1,
					pageSize: 10,
				},
				status: 'loadmore',
				triggered: false,
				downRefresh: false,
				pageCount: 0,

				isPlay: false,
				// tts播放实例
				ttsAudio: null,
			}
		},
		onLoad() {
			// 状态栏高度
			this.getSystemInfo();
		},
		onShow() {
			this.downRefresh = true
			this.shopList()
		},
		onUnload() {
			if (this.ttsAudio) {
				this.ttsAudio.stop();
				this.ttsAudio.destroy();
				this.ttsAudio = null;
			}
			// 重置所有项目的播放状态
			this.productList.forEach(item => item.isPlay = false);
			this.isPlay = false;
		},
		methods: {
			// 暂停播放
			zantingaClick(item) {
				if (this.ttsAudio) {
					this.ttsAudio.stop();
					item.isPlay = false;
					// 确保状态同步
					this.isPlay = false;
				}
			},
			/**
			 * 清理音频相关资源
			 */
			cleanupResources(audio) {
				if (audio) {
					audio.stop();
					audio.destroy();
				}
				this.ttsAudio = null;
				// 可选：重置所有 item 的播放状态
				this.productList.forEach(item => item.isPlay = false);
				this.isPlay = false;

				console.log('音频资源已清理');
			},
			base64ToArrayBuffer(base64) {
				const binaryString = atob(base64);
				const len = binaryString.length;
				const bytes = new Uint8Array(len);
				for (let i = 0; i < len; i++) {
					bytes[i] = binaryString.charCodeAt(i);
				}
				return bytes.buffer;
			},
			// 喇叭播放点击
			async labaClick(text, item) {
				// 如果已经有音频在播放，先停止
				if (this.ttsAudio) {
					this.ttsAudio.stop();
					this.ttsAudio.destroy();
					this.ttsAudio = null;
					// 重置所有项目的播放状态
					this.productList.forEach(i => this.$set(i, 'isPlay', false));
					this.isPlay = false;
				}

				try {
					const res = await getAliTtsSts();
					uni.request({
						url: 'https://nls-gateway-cn-shanghai.aliyuncs.com/stream/v1/tts',
						method: 'POST',
						header: {
							"Content-Type": "application/json"
						},
						data: {
							appkey: 's0aO8v0e4EFaPCv0',
							token: res.data.token,
							text: text,
							format: 'mp3',
							sample_rate: 16000,
							volume: 100
						},
						responseType: 'arraybuffer',
						success: async (ttsRes) => {
							// 创建新的音频实例
							const audio = uni.createInnerAudioContext();

							// #ifdef MP-WEIXIN
							audio.obeyMuteSwitch = false;
							uni.setInnerAudioOption({
								obeyMuteSwitch: false
							});
							const ttsPath = `${wx.env.USER_DATA_PATH}/tts${new Date().getTime()}.mp3`;
							// #endif

							// #ifdef APP-PLUS
							const ttsPath = `tts_${Date.now()}.mp3`;
							// #endif

							this.ttsAudio = audio;

							// 设置音频事件
							audio.onPlay(() => {
								console.log('音频开始播放');
								item.isPlay = true;
								this.isPlay = true;
							});

							audio.onStop(() => {
								console.log('音频停止播放');
								item.isPlay = false;
								this.isPlay = false;
							});

							audio.onEnded(() => {
								console.log('音频播放结束');
								item.isPlay = false;
								this.isPlay = false;
								// 清理临时文件
								try {
									// #ifndef APP-PLUS
									const fs = uni.getFileSystemManager();
									fs.unlinkSync(ttsPath);
									// #endif
									// #ifdef APP-PLUS
									plus.io.resolveLocalFileSystemURL(ttsPath, (entry) => {
										entry.remove(() => {
											console.log('文件删除成功');
										}, (e) => {
											console.error('文件删除失败', e);
										});
									});
									// #endif
								} catch (e) {
									console.error(e);
								}
								// 销毁音频实例
								audio.destroy();
								this.ttsAudio = null;
							});

							audio.onError((res) => {
								console.error('音频播放出错', res);
								item.isPlay = false;
								this.isPlay = false;
								// 清理资源
								try {
									// #ifndef APP-PLUS
									const fs = uni.getFileSystemManager();
									fs.unlinkSync(ttsPath);
									// #endif
									// #ifdef APP-PLUS
									plus.io.resolveLocalFileSystemURL(ttsPath, (entry) => {
										entry.remove(() => {
											console.log('文件删除成功');
										}, (e) => {
											console.error('文件删除失败', e);
										});
									});
									// #endif
								} catch (e) {
									console.error(e);
								}
								audio.destroy();
								this.ttsAudio = null;
							});
							// 写入文件并播放
							// #ifdef APP-PLUS
							try {
								const ttsPath = `tts_${Date.now()}.mp3`;

								// 写入文件
								const success = await this.writeFileToApp(ttsPath, ttsRes.data);
								if (success) {
									const fullPath = `_doc/${ttsPath}`;
									audio.src = fullPath;

									// 确保音频实例已正确初始化
									setTimeout(() => {
										audio.play()
										this.$set(item, 'isPlay', true); // 确保播放成功后更新
									}, 100);
								}
							} catch (e) {
								console.error('写入或播放失败:', e);
								this.cleanupResources(audio);
							}
							// #endif

							// #ifndef APP-PLUS
							// 小程序端使用 uni.getFileSystemManager()
							const fs = uni.getFileSystemManager();
							fs.writeFile({
								filePath: ttsPath,
								data: ttsRes.data,
								encoding: 'binary',
								success: () => {
									audio.src = ttsPath;
									setTimeout(() => {
										audio.play().catch(err => {
											console.error('播放失败', err);
											if (this.ttsAudio) {
												this.ttsAudio.destroy();
												this.ttsAudio = null;
											}
										});
									}, 100);
								},
								fail: (err) => {
									console.error('写入文件失败', err);
									audio.destroy();
									this.ttsAudio = null;
								}
							});
							// #endif


						},
						fail: (err) => {
							console.error('请求TTS失败', err);
							item.isPlay = false;
							this.isPlay = false;
						}
					});
				} catch (error) {
					console.error('获取TTS STS失败', error);
					item.isPlay = false;
					this.isPlay = false;
				}
			},

			// 将 ArrayBuffer 写入 APP 平台文件
			writeFileToApp(fileName, buffer) {
				return new Promise((resolve, reject) => {
					plus.io.resolveLocalFileSystemURL(
						"_doc/",
						(entry) => {
							entry.getFile(
								fileName, {
									create: true
								},
								(fileEntry) => {
									fileEntry.createWriter(
										(writer) => {
											writer.onwrite = () => {
												resolve(true)
											};
											writer.onerror = (err) => {
												console.error("写入错误详情:", err); // 打印错误对象
												reject(err);
											};
											const bases = uni.arrayBufferToBase64(buffer)
											writer.writeAsBinary(bases); // 确保传入 ArrayBuffer
										},
										(err) => {
											console.error("创建 Writer 失败:", err);
											reject(err);
										}
									);
								},
								(err) => {
									console.error("获取文件失败:", err);
									reject(err);
								}
							);
						},
						(err) => {
							console.error("解析文件系统失败:", err);
							reject(err);
						}
					);
				});
			},

			//触底加载
			lowerBottom() {
				if (this.queryParams.pageNum < this.pageCount) {
					if (!this.downRefresh) {
						this.downRefresh = true
						this.status = 'loading';
						this.queryParams.pageNum += 1
						this.shopList()
					}
				}
			},
			onRefresh() {
				this.triggered = true;
				this.downRefresh = true
				this.queryParams.pageNum = 1
				this.productList = []
				this.shopList()
			},
			onRestore() {
				this.triggered = false; // 需要重置
			},



			// 错题
			async shopList() {
				const res = await getIncorrect(this.queryParams)
				this.pageCount = res.total
				//停止加载中
				this.triggered = false;
				this.downRefresh = false
				//处理完逻辑停止刷新
				uni.stopPullDownRefresh();
				if (this.productList.length >= this.pageCount) {
					this.status = 'nomore';
				} else {
					let arr = [...this.productList, ...res.rows]
					this.productList = arr
					if (res.rows.length < 10) {
						this.status = 'nomore';
					}
				}
			}
		}
	}
</script>

<style lang="less" scoped>
	scroll-view ::-webkit-scrollbar {
		display: none !important;
	}

	.content {
		background-color: rgb(245, 245, 245);
		width: 100%;
		box-sizing: border-box;


		.box_scroll {
			height: 100%;
		}

		.box_list_noData {
			display: flex;
			flex-flow: column;
			align-items: center;

			.noData_img {
				width: 80%;
			}

			.noData_text {
				color: #B8BECA;
			}
		}

		.view {
			width: calc(100% - 60rpx);
			height: calc(100% - 60rpx);
			margin-top: 30rpx;
			box-sizing: border-box;
			padding: 30rpx;
			background-color: #fff;
			position: relative;
			top: 30rpx;
			margin: auto;
			overflow: auto;
			border-radius: 15px;

			.items {
				width: 100%;
				// height: 140rpx;
				border-bottom: 1px solid rgba(179, 173, 173, 0.2);
				display: flex;
				align-items: center;
				align-content: center;
				flex-wrap: wrap;
				box-sizing: border-box;
				padding: 20rpx 0;

				.header {
					width: 100%;
					display: flex;
					align-items: flex-start;
					justify-content: space-between;

					.title {
						font-size: 34rpx;
						flex: 1;
					}

					.pre {
						font-size: 26rpx;
						margin-left: 20rpx;
						margin-top: 10rpx;
					}


				}

				.bottom {
					width: 100%;
					display: flex;
					align-items: flex-start;
					justify-content: space-between;
					font-size: 24rpx;
					color: rgb(179, 173, 173);
					margin-top: 15rpx;

					.date {
						width: 250rpx;
					}
				}

				.correct_answers {
					color: red;
					font-size: 26rpx;
					display: flex;
					align-items: center;
					justify-content: flex-start;
					margin-top: 20rpx;
					width: 100%;

					.tiltes {
						margin-right: 25rpx;
					}
				}

				.answer_subject {
					margin-top: 20rpx;
					width: 100%;

					.font {
						font-size: 26rpx;
						display: flex;
						width: 100%;
						align-items: center;
						justify-content: space-between;

						.laba {
							width: 48rpx;
							height: 48rpx;
						}
					}

					.cometmt {
						font-size: 34rpx;
						color: rgb(179, 173, 173);
						line-height: 2;
						margin-top: 15rpx;
					}
				}
			}

		}
	}
</style>